$(function () {
	//折叠按钮切换
	(function () {
		$('.tab-content .sidebar-menu a').on('click', function () {
			if ($(this).is('.menu-dropdown')) {
				if ($(this).next('.submenu').css('display') == 'none') {
					$(this).find('.pull-right').removeClass('fa-angle-right').addClass('fa-plus-square-o');
					$(this).parent().siblings().find('.menu-dropdown .pull-right').removeClass('fa-plus-square-o').addClass('fa-angle-right');
				} else {
					$(this).find('.pull-right').removeClass('fa-plus-square-o').addClass('fa-angle-right');
				}
			} else {
				if (!$(this).find('i').is('.fa-plus-square-o')) {
					$(this).append('<i class="fa fa-plus-square-o pull-right"></i>');
					$(this).parent().siblings().find(':not(".menu-dropdown") .pull-right').remove('.fa-plus-square-o');
				}
			}
		});

		$('.tab-content  .sidebar-menu a').on('click', '.fa-plus-square-o', function (event) {
			event.stopPropagation();
		})
	})();


	/**
	 * 常用收款人
	 */
	(function () {
		//删除
		$("#commonReceiver .delete").click(function () {
			$(this).parent().parent().remove();
		});
	})();


	/**
	 * 费用类别
	 */
	(function () {
		//查看
		$('#costClasses .sidebar-menu').on('click', 'a', function () {
			$('.costInfo .widget-caption').text($(this).find('.menu-text').text());
			$('.costInfo').find('.costName').text($(this).find('.menu-text').text());
			$('.costInfo').find('.parentName').text($(this).parent().parent().parent().find("a").first().find("span").text());
			$('.costInfo').find('.type').text($(this).find('.type').val()=="1"?"收入":"支出");
			$('.costEdit').find('input[name=costclassName]').val($(this).find('.menu-text').text());
			$('.costEdit').find('input[name=parentName]').val($(this).parent().parent().parent().find("a").first().find("span").text());
			$('.costEdit').find('select[name=type]').find("option[text='"+$(this).find('.type').val()+"']").attr("selected",true);
			$('.costEdit').find('input[name=financeCostclassId]').val($(this).parent().find("a").find(".financeCostclassId").val());
			$('.costEdit').find('input[name=parentId]').val($(this).parent().find("a").find(".parentId").val());
			$('.costEdit').find('input[name=fullPath]').val($(this).find('.menu-text').text());
		});

		//新增
		$('#costClasses a').on('click', '.fa-plus-square-o', function () {
			if ($(this).is('.costClasses-btn')) {
				$('.costAdd input[name="parentName"]').val('无');
			} else {
				$('.costAdd input[name="parentName"]').val($(this).parent().find('.menu-text').text());
			}

			$('.costInfo,.costEdit').hide();
			$('.costAdd').show();

			//取消
			$('.costAdd .cancel-btn').on('click', function () {
				$('.costAdd,.costEdit').hide();
				$('.costInfo').show();
			})
		});


		//编辑
		$('.costInfo .edit-btn').on('click', function () {
			$('.costInfo,.costAdd').hide();
			$('.costEdit').show();

			//取消
			$('.cancel-btn').on('click', function () {
				$('.costInfo').show();
				$('.costEdit').hide();
			});
		})
	})();

	/**
	 * 审批流程
	 */
	(function () {
		//查看
		$('#approvalProcess .sidebar-menu').on('click', 'a', function () {
			$('.approvalInfo .widget-caption').text($(this).find('.menu-text').text());
			$.ajax({  
				   type: "POST",  
				   url: ctx + "/bizFinance/loadAppvoing",  
				   dataType: 'json',  
				   data:{financeCostclassId:$(this).find('.financeCostclassId').val()},
				   success: function(data){
					   $('#liuchengBody :not(.infoZhiwei)').html('');
					   $('#editAppend').html('');
					   if(data.length>0){
						   $('.approvalInfo .jobApplication').text(data[0].rightDuty.split("_")[0]);
						   $('#editRigtDuty').val(data[0].rightDuty.split("_")[0]);
						   $('#editRightDutyMin').val(data[0].rightDuty);
						   var json = JSON.parse(data[0].dutys);
						   var startNum = json[json.length-1].id;
						   startNum = startNum.replace("addHid","");
						   startNum = eval(startNum);
						   for(var i=0;i<json.length;i++){
							   $('#liuchengBody').append(' <tr>'
		                            	+'        <td class="col-xs-3 text-right">'
		                            	+'         '+(i+1)+'级审批职位：'
		                            	+'       </td>'
		                            	+'       <td class="oneApproval">'+json[i].name_value+'</td>'
		                            	+'   </tr>');
							   var div =   '<div class="form-group">'
								   		+'       <label class="control-label col-sm-2 no-padding-right">'+(i+1)+'级审批职位：</label>'
								   		+'		  <i class="fa fa-minus-square-o costClasses-btn" onclick="removeDiv(this)"></i>'
								   		+'      <div class="col-sm-8">'
								   		+'          <input name="addNumName" value="'+json[i].name_value+'" id="addNum'+startNum+'" onclick="showLiucheng(\'addNum'+startNum+'\',\'addHid'+startNum+'\')" class="form-control">'
								   		+'          <input name="addNumid" value="'+json[i].id_value+'" id="addHid'+startNum+'" type="hidden" >'
								   		+'          </input>'
								   		+'      </div>'
								   		+'   </div>';
							  $('#editAppend').append(div);
							  startNum++;
						   }
						   addNum = startNum;
					   }
				   }
			});
			
			$('.approvalEdit .widget-caption').text($(this).find('.menu-text').text());
		})
		//新增
		$('#approvalProcess a').on('click', '.fa-plus-square-o', function () {
			$('.approvalInfo,.costEdit').hide();
			$('.approvalAdd').show();
			
			
			//取消
			$('.approvalAdd .cancel-btn').on('click', function () {
				$('.approvalAdd,.approvalAddEdit').hide();
				$('.approvalInfo').show();
			})
		});
		//编辑
		$('.approvalInfo .edit-btn').on('click', function () {
			$('.approvalInfo .widget-caption').text($(this).find('.menu-text').text());
			$('.approvalInfo').hide();
			$('.approvalEdit').show();

			//取消
			$('.cancel-btn').on('click', function () {
				$('.approvalInfo').show();
				$('.approvalEdit').hide();
			});
		})
	})();
	init();
	initAddress();
	
	$('#costAdd').bootstrapValidator({
		fields: {/*验证*/
			costclassName: {
				message: 'The projectType is not valid',
				validators: {
					notEmpty: {/*非空提示*/
						message: '类型名称不能为空'
					}
				}
			}
		},
		submitHandler: function (validator, form, submitButton) {
			$.ajax({
				type: "POST",
				url: ctx + "/bizFinance/addNewRecordCostClass",
				data: $("#costAdd").serializeArray(),
				dataType: 'json',
				success: function(msg){
					if(msg.status == 'success'){
						toastr.success(msg.msg);
					}else{
						toastr.error(msg.msg);
					}

				}
			});
		}
	});
	
	$('#costEdit').bootstrapValidator({
		fields: {/*验证*/
			costclassName: {
				message: 'The projectType is not valid',
				validators: {
					notEmpty: {/*非空提示*/
						message: '类型名称不能为空'
					}
				}
			}
		},
		submitHandler: function (validator, form, submitButton) {
			$.ajax({
				type: "POST",
				url: ctx + "/bizFinance/updateRecordCostClass",
				data: $("#costEdit").serializeArray(),
				dataType: 'json',
				success: function(msg){
					if(msg.status == 'success'){
						toastr.success(msg.msg);
					}else{
						toastr.error(msg.msg);
					}

				}
			});
		}
	});
	
	$('#receiverAdd').bootstrapValidator({
		fields: {/*验证*/
			accountNum: {
				message: 'The projectType is not valid',
				validators: {
					notEmpty: {/*非空提示*/
						message: '类型名称不能为空'
					},
					regexp: {/* 只需加此键值对 */
						regexp: /^[0-9\.]+$/,
						message: '只能是数字'
					}
				}
			},
			accountName: {
				validators: {
					notEmpty: {/*非空提示*/
						message: '真实姓名不能为空'
					},
					regexp: {/* 只需加此键值对 */
						regexp: /[\u4e00-\u9fa5]/g,
						message: '只能是汉字'
					}
				}
			},
		},
		submitHandler: function (validator, form, submitButton) {
			$.ajax({
				type: "POST",
				url: ctx + "/bizFinance/addNewRecord",
				data: $("#receiverAdd").serializeArray(),
				dataType: 'json',
				success: function(msg){
					if(msg.status == 'success'){
						init();
						$('.receiverAdd').modal('hide');
					}else{
						toastr.error(msg.msg);
					}

				}
			});
		}
	});
	$('#receiverEdit').bootstrapValidator({
		fields: {/*验证*/
			accountNum: {
				message: 'The projectType is not valid',
				validators: {
					notEmpty: {/*非空提示*/
						message: '类型名称不能为空'
					},
					regexp: {/* 只需加此键值对 */
						regexp: /^[0-9\.]+$/,
						message: '只能是数字'
					}
				}
			},
			accountName: {
				validators: {
					notEmpty: {/*非空提示*/
						message: '真实姓名不能为空'
					},
					regexp: {/* 只需加此键值对 */
						regexp: /[\u4e00-\u9fa5]/g,
						message: '只能是汉字'
					}
				}
			},
		},
		submitHandler: function (validator, form, submitButton) {
			$.ajax({
				type: "POST",
				url: ctx + "/bizFinance/updateRecord",
				data: $("#receiverEdit").serializeArray(),
				dataType: 'json',
				success: function(msg){
					if(msg.status == 'success'){
						init();
						$('.receiverEdit').modal('hide');
					}else{
						toastr.error(msg.msg);
					}

				}
			});
		}
	});
	
	$('#approvalAdd').bootstrapValidator({
		fields: {/*验证*/
			addRightDutys: {
				message: 'The projectType is not valid',
				validators: {
					notEmpty: {/*非空提示*/
						message: '类型名称不能为空'
					}
				}
			}
		},
		submitHandler: function (validator, form, submitButton) {
			var ar1 = new Array();
        	$("input[id^=addNum]").each(function(){
        		var ob1 = {}; 
        		var id = this.id.substring(this.id.length-1,this.id.length);
        		ob1["id"] = "addHid"+id;
        		ob1["id_value"] = $("#addHid"+id).val();
        		ob1["name"] = this.id;
        		ob1["name_value"] = this.value;
        		ar1.push(ob1);
        	});
        	$("#addDutys").val(JSON.stringify(ar1));
        	$.ajax({
				type: "POST",
				url: ctx + "/bizFinance/addNewRecordApproving",
				data: $("#approvalAdd").serializeArray(),
				dataType: 'json',
				success: function(msg){
					if(msg.status == 'success'){
						toastr.success(msg.msg);
					}else{
						toastr.error(msg.msg);
					}

				}
			});
		}
	});
	$('#approvalEdit').bootstrapValidator({
		fields: {/*验证*/
			addRightDutys: {
				message: 'The projectType is not valid',
				validators: {
					notEmpty: {/*非空提示*/
						message: '类型名称不能为空'
					}
				}
			}
		},
		submitHandler: function (validator, form, submitButton) {
			var ar1 = new Array();
        	$("input[id^=addNum]").each(function(){
        		var ob1 = {}; 
        		var id = this.id.substring(this.id.length-1,this.id.length);
        		ob1["id"] = "addHid"+id;
        		ob1["id_value"] = $("#addHid"+id).val();
        		ob1["name"] = this.id;
        		ob1["name_value"] = this.value;
        		ar1.push(ob1);
        	});
        	$("#addDutys").val(JSON.stringify(ar1));
        	$.ajax({
				type: "POST",
				url: ctx + "/bizFinance/updateRecordApproving",
				data: $("#approvalEdit").serializeArray(),
				dataType: 'json',
				success: function(msg){
					if(msg.status == 'success'){
						toastr.success(msg.msg);
					}else{
						toastr.error(msg.msg);
					}

				}
			});
		}
	});
	
})
/**
 * 全选
 */
$(document).on('change', 'input:checkbox.master', function(){
	if($(this).prop('checked')){
		$('input:checkbox.slaver').prop('checked', 'checked');
	}else{
		$('input:checkbox.slaver').prop('checked', '');
	}
})
/**
 * 初始化
 * @returns
 */
function init (){
	var init = $('#commonReceiver').dataTable({
		"bAutoWidth" : false,
		"bFilter" : false,
		"iDisplayLength": 10,
		"bPaginate":true,
		"bSort": false, //是否支持排序功能
		"bLengthChange": false,
		"oLanguage" : {
			"sLengthMenu" : "每页显示 _MENU_ 条记录",
			"sZeroRecords" : "抱歉， 没有找到",
			"sInfo" : "从 _START_ 到 _END_ / 共 _TOTAL_ 条数据",
			"sInfoEmpty" : "",
			"sInfoFiltered" : "",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "前一页",
				"sNext" : "后一页",
				"sLast" : "尾页"
			},
			"sProcessing" : ""
		},
		"sAjaxSource" : ctx+'/bizFinance/load',
		"bDestroy" : true,
		"bRetrieve" : false,
		"bServerSide" : true,
		"fnServerData" : retrieveData,
		"aoColumns" : [
			{"mDataProp" : "financePayeeId",'sClass': "text-center","mRender": function ( data, type, full ) {
				return "<label> <input type='checkbox' class='slaver'> <span class='text'></span> </label>";
			}},
			{"mDataProp" : "accountName","bSortable": false,'sClass': "text-center"},
			{"mDataProp" : "phone","bSortable": false,'sClass': "text-center"},
			{"mDataProp" : "accountNum","bSortable": false,'sClass': "text-center"},
			{"mDataProp" : "bankName","bSortable": false,'sClass': "text-center"},
			{"mDataProp" : "province","bSortable": false,'sClass': "text-center"},
			{"mDataProp" : "city","bSortable": false,'sClass': "text-center"},
			{"mDataProp" : "ratio","bSortable": false,'sClass': "text-center","mRender": function ( data, type, full ) {
				return '<a onclick="cat(\''+full["financePayeeId"]
					+'\',\''+full["accountName"]
					+'\',\''+full["accountNum"]
					+'\',\''+full["bankName"]
					+'\',\''+full["province"]
					+'\',\''+full["city"]
					+'\',\''+full["phone"]
					+'\',\''+full["description"]
					+'\')" class="btn btn-warning btn-xs edit" data-toggle="modal" data-target=".receiverView">'
					+'<i class="fa fa-edit"></i> 查看</a>'
					+'<a onclick="edit(\''+full["financePayeeId"]
					+'\',\''+full["accountName"]
					+'\',\''+full["accountNum"]
					+'\',\''+full["bankName"]
					+'\',\''+full["provinceId"]
					+'\',\''+full["cityId"]
					+'\',\''+full["phone"]
					+'\',\''+full["description"]
					+'\')" data-toggle="modal" data-target=".receiverEdit" class="btn btn-info btn-xs edit">'
					+'<i class="fa fa-edit"></i> 编辑</a>'
					+'<a href="javascript:void(0);" onclick="del(\''+full["financePayeeId"]+'\')" class="btn btn-danger btn-xs delete">'
					+'    <i class="fa fa-trash-o"></i> 删除</a>'
			}}],
		"aoColumnDefs" : [{
			sDefaultContent: '',
			aTargets: [ '_all' ]
		}]
	});
}

/**
 * 回调函数
 * @param sSource
 * @param aoData
 * @param fnCallback
 * @returns
 */
function retrieveData(sSource, aoData, fnCallback, oSettings ){
	/**
	 * 参数添加
	 */
	aoData.push( { "name": "pageNum", "value": (Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength )+1) });
	aoData.push( { "name": "pageSize", "value": oSettings._iDisplayLength });
	if($("#searchVal").val()=="启用"){
		aoData.push( { "name": "enable", "value": 1} );
	}
	else if($("#searchVal").val()=="禁用"){
		aoData.push( { "name": "enable", "value": 0} );
	}else{
		aoData.push( { "name": "searchVal", "value": $("#searchVal").val()} );
	}
	$.ajax({
		"type" : "Post",
		"url" : sSource,
		"dataType" : "json",
		"data" : aoData,
		"success" : function(resp) {
			fnCallback(resp.returnObject);
		}
	});
}
/**
 * 地址初始化
 * @returns
 */
function initAddress(){
	$("#province2").change(function(){
		city(this.value);
	});
	province();
}
function province(){
	document.getElementById("city2").options.length=0;
	$.ajax({
		url:ctx+"/address/ajaxLoad",
		data:{"addressId":0},
		dataType:"json",
		async:true,
		success:function(data){
			for(var i=0;i<data.length;i++){
				var o = new Option(data[i].fullName,data[i].addressId);
				document.getElementById("province2").options.add(o);
			}
	//			city(data[0].addressId);
		}
	})
}
function city(val){
	document.getElementById("city2").options.length=0;
	$.ajax({
		url:ctx+"/address/ajaxLoad",
		data:{"addressId":val},
		dataType:"json",
		async:true,
		success:function(data){
			if(data.length>0){
				for(var i=0;i<data.length;i++){
					var o = new Option(data[i].fullName,data[i].addressId);
					document.getElementById("city2").options.add(o);
				}
			}
		}
	})
}
/**
 * 查看
 * @returns
 */
function cat(financePayeeId,accountName,accountNum,bankName,province,city,phone,description){
	$('#catFinancePayeeId').val(financePayeeId);
	$('#catAccountName').val(accountName);
	$('#catAccountNum').val(accountNum);
	$('#catBankName').val(bankName);
	$('#catPhone').val(phone);
	$('#catDescription').val(description);
	$('#catProvince').val(province);
	$('#catCity').val(city);
}
/**
 * 编辑
 * @returns
 */
function edit(financePayeeId,accountName,accountNum,bankName,provinceId,cityId,phone,description){
	$('#updateFinancePayeeId').val(financePayeeId);
	$('#updateAccountName').val(accountName);
	$('#updateAccountNum').val(accountNum);
	$('#updateBankName').val(bankName);
	$('#updatePhone').val(phone);
	$('#updateDescription').val(description);
	$("#province1").change(function(){
		updateCity(this.value);
	});
	updateProvince(provinceId,cityId);
}
function updateProvince(id1,id2){
	document.getElementById("city1").options.length=0;
	$.ajax({
		url:ctx+"/address/ajaxLoad",
		data:{"addressId":0},
		dataType:"json",
		async:true,
		success:function(data){
			for(var i=0;i<data.length;i++){
				var o = new Option(data[i].fullName,data[i].addressId);
				var choose = (data[i].addressId == id1);
				if(choose){
					o.selected = true;
				}
				document.getElementById("province1").options.add(o);
			}
			updateCity(id1,id2);
		}
	})
}
function updateCity(id1,id2){
	document.getElementById("city1").options.length=0;
	$.ajax({
		url:ctx+"/address/ajaxLoad",
		data:{"addressId":id1},
		dataType:"json",
		async:true,
		success:function(data){
			if(data.length>0){
				for(var i=0;i<data.length;i++){
					var o = new Option(data[i].fullName,data[i].addressId);
					if(data[i].addressId == id2){
						o.selected = true;
					}
					document.getElementById("city1").options.add(o);
				}
			}
		}
	})
}
function del(val){
	$.ajax({
		url: ctx + '/bizFinance/deleteRecord',
		type: 'POST',
		data: {
			financePayeeId:val,
		},
		dataType: 'json',
		success: function (data) {
			if(data.status == 'success'){
				toastr.success(data.msg);
				init();
			}
		}
	});
}
//******************************************************************************************************************************************************
//费用类别
$(function(){
	initCostClass(0);
})
//费用类别左侧列表初始化
function initCostClass(pId){
	$.ajax({  
		   type: "POST",  
		   url: ctx + "/bizFinance/loadCostClass",  
		   dataType: 'json',  
		   data:{parentId:pId},
		   success: function(data){
			   var str = "";
			   $('#listMenu').html("");
			   for(var i=0; i<data.length; i++){
           			str = str + '<li>'
			             +'   <a href="#" onclick="appendCostClass(\''+data[i].financeCostclassId+'\',this)" class="menu-dropdown">'
			             +'   <img src="'+ctx_static+'/home/configuration/image/teach.png"'
			             +'        alt="">'
			             +'   <span class="menu-text">'+data[i].costclassName+'</span>'
			             +'   <i class="fa pull-right fa-plus-square-o"></i>'
			             +'<input type="hidden" value="'+data[i].parentId+'" class="parentId" name="parentId">'
			             +'<input type="hidden" value="'+data[i].fullPath+'" class="fullPath" name="fullPath">'
			             +'<input type="hidden" value="'+data[i].type+'" class="type" name="type">'
			             +'<input type="hidden" value="'+data[i].financeCostclassId+'" class="financeCostclassId" name="financeCostclassId">'
		             +' </a><ul class="submenu"></ul></li>';	
           			$('#listMenu').html(str);
           		}
		   }  
		});  
}
function appendCostClass(pId,e){
	$.ajax({  
		   type: "POST",  
		   url: ctx + "/bizFinance/loadCostClass",  
		   dataType: 'json',  
		   data:{parentId:pId},
		   success: function(data){
			   var str = "";
			   for(var i=0; i<data.length; i++){
        		str = str + '<li>'
		             +'   <a href="#" onclick="appendCostClass(\''+data[i].financeCostclassId+'\',this)" class="menu-dropdown">'
		             +'   <span class="menu-text">'+data[i].costclassName+'</span>'
		             +'   <i class="fa pull-right fa-plus-square-o"></i>'
		             +'<input type="hidden" value="'+data[i].parentId+'" class="parentId" name="parentId">'
		             +'<input type="hidden" value="'+data[i].fullPath+'" class="fullPath" name="fullPath">'
		             +'<input type="hidden" value="'+data[i].type+'" class="type" name="type">'
		             +'<input type="hidden" value="'+data[i].financeCostclassId+'" class="financeCostclassId" name="financeCostclassId">'
		             +' </a><ul class="submenu"></ul></li>';	
        		$(e).parent().children("ul").html(str);
			   }
		   }  
		}); 
}
//新增费用类别
$('#costClasses a').on('click', '.fa-plus-square-o', function (e) {
	
	//alert($(this).siblings('input[name="financeCostclassId"]').val());
	
	alert(1);
	
	if ($(this).is('.costClasses-btn')) {
		$('.costAdd input[name="parentName"]').val('无');
		$('.costAdd input[name="parentId"]').val(0);
	} else {	
		$('.costAdd input[name="parentName"]').val($(this).parent().children('.menu-text').text());
		$('.costAdd input[name="parentId"]').val($(this).parent().children('.parentId').val());
		$('.costAdd input[name="fullPath"]').val($(this).parent().children('.fullPath').val()+$(this).parent().children('.parentId').val()+",");
	}

	$('.costInfo,.costEdit').hide();
	$('.costAdd').show();
	
	e.stopPropagation();

/*	//取消
	$('.costAdd .cancel-btn').on('click', function () {
		$('.costAdd,.costEdit').hide();
		$('.costInfo').show();
	})*/
});
function showMenu(){
	var cityObj = $("#ediParentName");
	var cityOffset = $("#ediParentName").offset();
	$("#content").css({left:cityOffset.left + "px", top:eval(cityOffset.top-90)+ "px"}).slideDown("fast");
	$("body *:not(.menuContent)").bind("mousedown", onBodyDown);
	
	$('#ajaxTree').width(cityObj.width()+12);
	$.ajax({
        type:"post",
        url:ctx+"/bizFinance/loadCostClassTree",
		dataType : "json",
		success : function(date) {
			$.fn.zTree.init($("#ajaxTree"),setting, date);
		}
	});
}
function onClick(e, treeId, treeNode) {
	$('#ediParentName').val(treeNode.name);
	$('#editParentId').val(treeNode.id);
	$('#editFullPath').val(treeNode.type);
}
var setting = {
		view:{
			showIcon:false,
			showLine:false,
			expandSpeed:"normal"
		},
		data: {
			simpleData: {
				enable: true,
				idKey:"id",
				pIdKey:"pId"
			}
		},
		callback: {
			onClick: onClick
		}
	};
//******************************************************************************************************************************************************
//审批流程
$(function(){
	initPayeeClass(0);
})
function initPayeeClass(pId){
	$.ajax({  
		   type: "POST",  
		   url: ctx + "/bizFinance/loadCostClass",  
		   dataType: 'json',  
		   data:{parentId:pId},
		   success: function(data){
			   var str = "";
			   for(var i=0; i<data.length; i++){
           		str = str + '<li>'
		             +'   <a href="#" onclick="appendPayee(\''+data[i].financeCostclassId+'\',this)" class="menu-dropdown">'
		             +'   <img src="'+ctx_static+'/home/configuration/image/teach.png"'
		             +'        alt="">'
		             +'   <span class="menu-text">'+data[i].costclassName+'</span>'
		             +'   <i class="fa pull-right fa-plus-square-o"></i>'
		             +'<input type="hidden" value="'+data[i].financeCostclassId+'" class="parentId" name="parentId">'
		             +'<input type="hidden" value="'+data[i].fullPath+'" class="fullPath" name="fullPath">'
		             +'<input type="hidden" value="'+data[i].type+'" class="type" name="type">'
		             +'<input type="hidden" value="'+data[i].financeCostclassId+'" class="financeCostclassId" name="financeCostclassId">'
		             +' </a><ul class="submenu"></ul></li>';	
           		$('#liuchengMenu').html(str);
           	}
			   initAddPayee();
		   }  
		});  
}
function appendPayee(pId,e){
	$.ajax({  
		   type: "POST",  
		   url: ctx + "/bizFinance/loadCostClass",  
		   dataType: 'json',  
		   data:{parentId:pId},
		   success: function(data){
			   var str = "";
			   for(var i=0; i<data.length; i++){
        		str = str + '<li>'
		             +'   <a href="#" onclick="appendPayee(\''+data[i].financeCostclassId+'\',this)" class="menu-dropdown">'
		             +'   <span class="menu-text">'+data[i].costclassName+'</span>'
		             +'   <i class="fa pull-right fa-plus-square-o"></i>'
		             +'<input type="hidden" value="'+data[i].financeCostclassId+'" class="parentId" name="parentId">'
		             +'<input type="hidden" value="'+data[i].fullPath+'" class="fullPath" name="fullPath">'
		             +'<input type="hidden" value="'+data[i].type+'" class="type" name="type">'
		             +'<input type="hidden" value="'+data[i].financeCostclassId+'" class="financeCostclassId" name="financeCostclassId">'
		             +' </a><ul class="submenu"></ul></li>';	
        		$(e).parent().children("ul").html(str);
        	}
			   initAddPayee();
		   }  
		}); 
}
function initAddPayee(){
	//新增
	$('#approvalProcess a').on('click', '.fa-plus-square-o', function () {
		$('.approvalAdd .widget-caption').text($(this).parent().children('.menu-text').text());
		$('.approvalAdd').find("input[name=financeCostclassId]").val($(this).parent().children('.financeCostclassId').val());
		$('.approvalInfo,.costEdit').hide();
		$('.approvalAdd').show();

		//取消
		$('.approvalAdd .cancel-btn').on('click', function () {
			$('.approvalAdd,.approvalAddEdit').hide();
			$('.approvalInfo').show();
		})
	});
}
var addNum = 0;
function addDiv(){
	var str = '<div class="form-group">'
			 +'       <label class="control-label col-sm-2 no-padding-right">审批职位</label>'
			 +'		  <i class="fa fa-minus-square-o costClasses-btn" onclick="removeDiv(this)"></i>'
			 +'      <div class="col-sm-8">'
			 +'          <input name="addNumName" id="addNum'+addNum+'" onclick="showLiucheng(\'addNum'+addNum+'\',\'addHid'+addNum+'\')" class="form-control">'
			 +'          <input name="addNumid" id="addHid'+addNum+'" type="hidden" >'
			 +'          </input>'
			 +'      </div>'
			 +'   </div>';
	$('#addDiv').append(str);
	addNum++;
}
function removeDiv(e){
	$(e).parent().remove();
}
function showDutys(){
	$('#approvalAdd').bootstrapValidator('resetForm', false);
	var cityObj = $("#addRightDutys");
	var cityOffset = $("#addRightDutys").offset();
	$("#content").css({left:cityOffset.left + "px", top:eval(cityOffset.top-90)+ "px"}).slideDown("fast");
	$("body *:not(.menuContent)").bind("mousedown", onBodyDown);
	
	$('#ajaxTree').width(cityObj.width()+12);
	$.ajax({
        type:"post",
        url:ctx+"/user/ajaxLoadMaterTree",
		dataType : "json",
		success : function(date) {
			$.fn.zTree.init($("#ajaxTree"),settingDutys, date);
		}
	});
}
var settingDutys = {
		view:{
			showIcon:false,
			showLine:false,
			expandSpeed:"normal",
			dblClickExpand: false
		},
		check: {
			enable: true,
			chkboxType: {"Y":"", "N":""}
		},
		data: {
			simpleData: {
				enable: true,
				idKey:"id",
				pIdKey:"pId"
			}
		},
		callback: {
			onCheck: onClickDutys
		}
	};
function onClickDutys(e, treeId, treeNode) {
	
	var zTree = $.fn.zTree.getZTreeObj("ajaxTree"),
	nodes = zTree.getCheckedNodes(true),
	v = "";
	v1 = "";
	for (var i=0, l=nodes.length; i<l; i++) {
		if(nodes[i].type == "4"){
			v += nodes[i].name + ",";
			v1 += nodes[i].id + ",";
		}
	}
	if (v.length > 0 ) v = v.substring(0, v.length-1);
	if (v1.length > 0 ) v1 = v1.substring(0, v1.length-1);
	var cityObj = $("#addRightDutys");
	cityObj.attr("value", v);
	var o1 = $("#rightDuty");
	o1.attr("value", v+"_"+v1);
}
var settingliucheng = {
		view:{
			showIcon:false,
			showLine:false,
			expandSpeed:"normal"
		},
		data: {
			simpleData: {
				enable: true,
				idKey:"id",
				pIdKey:"pId"
			}
		},
		callback: {
			onClick: onClickliucheng
		}
	};
var publicId = "";
var publicHId = "";
function showLiucheng(id,hid){
	publicId = id;
	publicHId = hid;
	var cityObj = $("#"+id);
	var cityOffset = $("#"+id).offset();
	$("#content").css({left:cityOffset.left + "px", top:eval(cityOffset.top-90)+ "px"}).slideDown("fast");
	$("body *:not(.menuContent)").bind("mousedown", onBodyDown);
	
	$('#ajaxTree').width(cityObj.width()+12);
	$.ajax({
        type:"post",
        url:ctx+"/user/ajaxLoadMaterTree",
		dataType : "json",
		success : function(date) {
			$.fn.zTree.init($("#ajaxTree"),settingliucheng, date);
		}
	});
}
function onClickliucheng(e, treeId, treeNode) {
	if(treeNode.type =="4"){
		$("#"+publicId).val(treeNode.name);
		$("#"+publicHId).val(treeNode.id);
	}
}
//回车搜索
function search(){
	if(event.keyCode==13){
		init();
	}
}